package cn.aion.crawlers;

import cn.aion.dao.ProjectVideoDAO;
import cn.aion.dao.VideoDataDAO;
import cn.aion.model.ProjectVideo;
import cn.aion.model.ToutiaoVideo;
import cn.aion.model.VideoData;
import cn.aion.util.Helper;
import cn.wanghaomiao.seimi.annotation.Crawler;
import cn.wanghaomiao.seimi.def.BaseSeimiCrawler;
import cn.wanghaomiao.seimi.struct.Request;
import cn.wanghaomiao.seimi.struct.Response;
import cn.wanghaomiao.xpath.model.JXDocument;
import com.alibaba.fastjson.JSON;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;

import java.util.List;

/**
 * 今日头条扫描规则
 * Created by 虚空之翼 on 2016/12/14.
 */
@Crawler(name = "toutiao", useUnrepeated = false)
public class Toutiao extends BaseSeimiCrawler {
    @Autowired
    private ProjectVideoDAO projectVideoDAO;
    @Autowired
    private VideoDataDAO videoDataDAO;

    @Override
    public String[] startUrls() {
        return new String[]{"http://www.van-cool.com/admin/base/scan"};
    }

    @Override
    public void start(Response response) {
        main();
    }

    @Scheduled(cron = "0 0 0/1 * * ?")
    public void main() {
        logger.info("开启今日头条扫描任务");
        try {
            List<ProjectVideo> list = projectVideoDAO.getVideoAll();
            for (ProjectVideo video : list) {
                String url = video.getToutiaoUrl();
                if (url != null && !url.isEmpty()) {
                    logger.info("扫描地址：{}", url);
                    push(Request.build(url, "fetchData"));
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void fetchData(Response response){
        JXDocument doc = response.document();

        // 根据URL获取视频ID
        ProjectVideo projectVideo = projectVideoDAO.selectOneByToutiao(response.getUrl());
        try {
            String script = StringUtils.join(doc.sel("//script/outerHtml()"),"");
            script = script.substring(script.indexOf("abstract={")+9);
            script = script.substring(0, script.indexOf("};")+1);
            if (!script.equals("")) {
                ToutiaoVideo toutiao = JSON.parseObject(script, cn.aion.model.ToutiaoVideo.class);
                logger.info("{} | 播放数：{}", toutiao.getTitle(), toutiao.getCount());

                // 计算当日的递增数量
                VideoData preData = videoDataDAO.selectOnePrevious(projectVideo.getId(), 6);
                Integer playCount = toutiao.getCount();
                Integer addCount = playCount;
                if (preData != null) {
                    addCount = playCount - preData.getPlayCount();
                }

                // 如果当天已经抓取过数据就更新数据
                VideoData videoData = videoDataDAO.selectOneToday(projectVideo.getId(), 6);
                if (videoData != null) {
                    if (playCount != 0) {
                        videoData.setPlayCount(playCount);
                        videoData.setPlayAdd(addCount);
                        videoDataDAO.update(videoData);
                    }
                } else {
                    VideoData newData = new VideoData();
                    newData.setPlayCount(playCount);
                    newData.setPlayAdd(addCount);
                    newData.setVideoId(projectVideo.getId());
                    newData.setSrcType(6);
                    videoDataDAO.save(newData);
                }
                // 更新总数据
                if (playCount != 0) {
                    projectVideoDAO.updateToutiaoVideoCount(projectVideo.getId(), playCount);
                    projectVideoDAO.updateTotal(projectVideo.getId());
                    projectVideoDAO.updateApplyTotal(projectVideo.getProjectId(), projectVideo.getAnchorId(), Helper.getVideoTotal(projectVideo));
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
